/**
 * Created by Administrator on 2018/10/8.
 */

+function ($) {

    var ExtDateRange = function (f, e) {
        this.$element = $(f);
        this.options = $.extend({}, ExtDateRange.DEFAULTS, this.$element.data(), e);
        this.init()
    };
    ExtDateRange.DEFAULTS = {
        "showDropdowns": true,
        "linkedCalendars": false,
        locale: {
            "maxSpan": {
                "days": 7
            },
            "separator": " ~ ",
            "applyLabel": "确定",
            "cancelLabel": "取消",
            format: 'YYYY-MM-DD'
        }
    };
    ExtDateRange.prototype.init = function () {
        var iconButton = this.$element.parent().find(".input-group-addon");
        var dateRangePicker ,options = this.options;
        if (options.format == "YYYY-MM-DD HH:mm:SS") {
            options.timePicker = true;
        }
        options.locale.format = options.format;
        options.toggle=this.$element;

        dateRangePicker = this.$element.daterangepicker(options, function (start, end, label) {
            if(options.startName && options.endName ){
                $(":input[name='"+options.startName+"']").val(start.format( options.locale.format));
                $(":input[name='"+options.endName+"']").val(end.format( options.locale.format));
            }
        });
        if(iconButton.length > 0){
            iconButton.on("click",function(e){
               dateRangePicker.data('daterangepicker').show(e);
            })
        }
        if(options.startName && options.endName ){
            this.$element.parent().append("<input type='hidden' name='"+options.startName+ "'>")
            this.$element.parent().append("<input type='hidden' name='"+options.endName+ "'>")
        }
    }
    function Plugin(e) {
        Bolt.assert($.fn.datetimepicker, "依赖组件 datetimepicker 未引入");
        return this.each(function () {
            var h = $(this);
            var g = h.data("extDateRange");
            var f = typeof e == "object" && e;
            if (!g) {
                h.data("extDateRange", (g = new ExtDateRange(this, f)))
            }
            if (typeof e == "string") {
                g[e]()
            }
        })
    }

    $.fn.extDateRange = Plugin
    $.fn.extDateRange.Constructor = ExtDateRange;

    Bolt.addComponent({
        name: "ExtDateRange",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "input[data-toggle='dateRange']",
        order: 800
    })
}(jQuery);